`
Streams
Streams are files that act as communication channels between a
program and its environment. When you interact with a program
(whether a built-in Linux utility such as ls or mkdir or one that
you wrote yourself), you’re interacting with one or more streams. In
bash, there are three standard data streams, as shown in Table 1-4.
Table 1-4
Streams
Stream name
Description
File descriptor number
Standard Input (stdin)
Data coming into some program
as input
0
Standard Output (stdout)
Data coming out of a program
1
Standard Error (stderr)
Errors coming out of a program
2
So far, we’ve run a few commands from the terminal and written
and executed a simple script. The generated output was all sent to the
standard output stream (stdout), or in other words, your terminal
screen.
Scripts can also receive commands as input. When a script is
designed to receive input, it reads it from the standard input stream
(stdin). Lastly, scripts may display error messages to the screen due
to a bug or syntax error in the commands sent to it. These messages
are sent to the standard error stream (stderr).
To illustrate streams, we’ll use the mkdir command to create a
few directories and then use ls to list the content of the current
directory. Open your terminal and execute the following command:
$ mkdir directory1 directory2 directory1
mkdir: cannot create directory 'directory1': File exists
$ ls -l
total 1
drwxr-xr-x 1 user user 0 Feb 17 09:45 directory1
drwxr-xr-x 1 user user 0 Feb 17 09:45 directory2
Notice that the mkdir command generated an error. This is
because we passed the directory name directory1 twice on the
command line. So, when mkdir ran, it created directory1, created
directory2, and then failed on the third argument because, at that
point, directory1 had already been created. These types of errors are
sent to the standard error stream.
Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks